<template>
  <div class="date">
    <template v-if="hours > 0">
      {{ hours }}:{{ min }}:{{ sec }}
    </template>
    <template v-else>
      {{ hours }}:{{ min }}:{{ sec }}
    </template>
  </div>
</template>

<script>
export default {
  name: "count-down",
  props: {
    currentTime: {
      type: [String, Number],
      default: 0
    },
    endTime: {
      type: [String, Number],
      default: 0
    },
  },
  data() {
    return {
      hours: '00',
      min: '00',
      sec: '00',
    }
  },
  created() {
    this.countDown(this.currentTime, this.endTime)
  },
  methods: {
    timeFormat(param) {
      return param < 10 ? '0' + param : param;
    },
    countDown(newTime, endTime) {
      clearInterval(this.interval);
      this.interval = null;
      this.interval = setInterval(() => {
        // 对结束时间进行处理渲染到页面
        let obj = null;
        // 如果活动未结束，对时间进行处理
        if (endTime - newTime > 0) {
          let time = endTime - newTime;
          // 获取时、分、秒
          let hours = parseInt(time / (1000 * 3600));
          let remainingSeconds = time % (1000 * 3600);
          let min = parseInt(remainingSeconds / (1000 * 60));
          let sec = parseInt((remainingSeconds % (1000 * 60)) / 1000);
          obj = {
            hours: this.timeFormat(hours),
            min: this.timeFormat(min),
            sec: this.timeFormat(sec)
          };
          newTime += 1000;
        } else { // 活动已结束，全部设置为'00'
          obj = {
            hours: '00',
            min: '00',
            sec: '00'
          };
          clearInterval(this.interval);
        }
        this.hours = obj.hours;
        this.min = obj.min;
        this.sec = obj.sec;
      }, 1000);
    },
  }
}
</script>

<style scoped lang="less">
.date {
  white-space: nowrap;
}
</style>